# 24. 两两交换链表中的节点
# 给你一个链表，两两交换其中相邻的节点，并返回交换后链表的头节点。你必须在不修改节点内部的值的情况下完成本题（即，只能进行节点交换）。

# Definition for singly-linked list.
# 输入：head = [1,2,3,4]
# 输出：[2,1,4,3]
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next
class Solution:
    # 一开始琢磨出的写法，八九不离十
    def swapPairs(self, head: [ListNode]) -> [ListNode]:
        node_list = []
        dummy = ListNode()
        dummy.next = head
        cur = dummy
        while cur.next != None and cur.next.next != None:
            cn_a = cur.next
            cn_b = cur.next.next.next
            cur.next = cur.next.next
            cur.next.next = cn_a
            cur.next.next.next = cn_b
            cur = cur.next.next
        return dummy.next

    #这里是看过卡哥视频后的写法，删除了一个没用的列表，变量定义更简洁了
    def swapPairss(self, head: [ListNode]) -> [ListNode]:
        dummy = ListNode()
        dummy.next = head
        cur = dummy
        while cur.next != None and cur.next.next != None:
            cn_a = cur.next
            cn_b = cur.next.next.next
            cur.next = cur.next.next
            cur.next.next = cn_a
            cn_a.next = cn_b
            cur = cur.next.next
        return dummy.next

if __name__ == '__main__':
    a = ListNode(1)
    b = ListNode(2)
    c = ListNode(3)
    d = ListNode(4)
    e = ListNode(5)
    a.next = b
    b.next = c
    c.next = d
    d.next = e
    ss = Solution()
    rr = ss.swapPairs(a)
    while rr != None:
        print(rr.val)
        rr = rr.next
